<?php
namespace Dry\Base;

class SessionHandler {

    private $pdo = null;

    private $lifeTime = 1440;

    public function __construct($pdo)
    {
        $this->pdo = $pdo;
        $this->lifeTime = get_cfg_var('session.gc_maxlifetime');
        session_set_save_handler(
            array($this, 'open'),
            array($this, 'close'),
            array($this, 'read'),
            array($this, 'write'),
            array($this, 'destroy'),
            array($this, 'gc')
        );
        register_shutdown_function('session_write_close');
    }

    public function open($save_path, $session_name)
    {
        return true;
    }

    public function close()
    {
        return true;
    }

    public function read($session_id)
    {
        $time = date('Y-m-d H:i:s');
        $sql = "select session_data from session_handler where session_id='{$session_id}' and session_expires>'{$time}' limit 1";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        if($sm->rowCount()){
            $result = $sm->fetch();
            return $result['session_data'];
        }
        else{
            return '';
        }
    }

    public function write($session_id, $session_data)
    {
        $time = date('Y-m-d H:i:s', time()+$this->lifeTime);
        $sql = "select count(1) as total from session_handler where session_id='{$session_id}' limit 1";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        if($sm->fetchColumn()){
            $sql = "update session_handler set session_data='{$session_data}',session_expires='{$time}' where session_id='{$session_id}'";
        }
        else{
            $sql = "insert into session_handler(session_id,session_data,session_expires) values('{$session_id}','{$session_data}','{$time}')";
        }
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        return true;
    }

    public function destroy($session_id)
    {
        $sql = "delete from session_handler where session_id='{$session_id}'";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        return true;
    }

    public function gc($maxlifetime)
    {
        $time = date('Y-m-d H:i:s', time()-$maxlifetime);
        $sql = "delete from session_handler where session_expires<'{$time}'";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        return true;
    }

}
?>
